<template>
  <div class="map-container">
    <h1>WFS Demo</h1>
    <div id="map" ref="mapContainer" class="map"></div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Style from 'ol/style/Style.js';
import Stroke from 'ol/style/Stroke.js';
import Fill from 'ol/style/Fill.js';
import OSM from 'ol/source/OSM.js';

const mapContainer = ref(null);
let map = null;

onMounted(() => {
  // 创建WFS矢量图层
  const vectorSource = new VectorSource({
    format: new GeoJSON(),
    url: '/api/geoserver/testmap/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=testmap%3Abou2_4l&outputFormat=application%2Fjson&count=-1'
  });

  // 添加数据源加载错误处理
  vectorSource.on('error', (event) => {
    console.error('WFS数据加载失败:', event.error);
    alert('WFS图层加载失败，请检查服务地址和网络连接');
  });

  // 添加数据源变化监听
  vectorSource.on('change', () => {
    if (vectorSource.getState() === 'ready') {
      console.log('WFS数据加载成功，要素数量:', vectorSource.getFeatures().length);
      
      // 如果有要素，自动调整视图范围
      if (vectorSource.getFeatures().length > 0) {
        const extent = vectorSource.getExtent();
        if (extent && extent[0] !== Infinity) {
          map.getView().fit(extent, {
            padding: [50, 50, 50, 50],
            maxZoom: 10
          });
        }
      }
    }
  });

  const vectorLayer = new VectorLayer({
    source: vectorSource,
    style: (feature, resolution) => {
      return new Style({
        stroke: new Stroke({
          color: 'blue',
          width: 1
        }),
        fill: new Fill({
          color: 'rgba(0, 0, 255, 0.1)'
        })
      });
    }
  });

  // 初始化地图 - 设置为中国区域的默认中心点
  map = new Map({
    layers: [
      new TileLayer({
        source: new OSM()
      }),
      vectorLayer
    ],
    target: mapContainer.value,
    view: new View({
      // 中国区域的默认中心点（北京附近）
      center: [104.1954, 35.8617],
      maxZoom: 19,
      zoom: 4,
      projection: 'EPSG:4326'
    })
  });

  // 测试直接访问API地址（可选）
  testWfsApi();
});

// 单独测试WFS API是否可访问
function testWfsApi() {
  const wfsUrl = '/api/geoserver/testmap/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=testmap%3Abou2_4l&outputFormat=application%2Fjson';
  
  fetch(wfsUrl)
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .then(data => {
      console.log('WFS API测试成功，返回数据:', data);
    })
    .catch(error => {
      console.error('WFS API测试失败:', error);
      console.log('请检查以下几点:');
      console.log('1. 代理配置是否正确（vue.config.js）');
      console.log('2. GeoServer服务是否运行');
      console.log('3. 工作空间、图层名称是否正确');
    });
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  margin: 10px 0;
  color: #333;
}

.map {
  flex: 1;
  width: 100%;
  min-height: 500px;
  border: 1px solid #ccc;
}
</style>